package com.xuanyuanxinyu.core.extension

import android.app.Activity
import android.content.Intent
import android.content.res.Resources
import android.os.Looper
import android.util.TypedValue
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * Describe:kotlin扩展属性及扩展方法相关
 * Created by ken on 2022/10/6
 */


fun Activity.startActivity(clazz: Class<*>) {
    startActivity(Intent(this, clazz))
}


/**
 * MutableLiveData扩展方法，根据当前线程自动选择update or set
 */
fun <T> MutableLiveData<T>.updateValue(value: T?, alwaysChange: Boolean = true) {
    if (!alwaysChange) {
        if (this.value == value) {
            return
        }
    }
    if (Thread.currentThread() != Looper.getMainLooper().thread) {
        this.postValue(value)
    } else {
        this.value = value
    }
}

/**
 * MutableLiveData扩展方法，List添加元素可供外界监听
 */
fun <T> MutableLiveData<MutableList<T>>.updateList(value: T) {
    var list = this.value
    if (list == null) {
        list = mutableListOf()
    }
    list.add(value)
    this.updateValue(list)
}

/**
 * Float将dp转为px
 */
val Float.dp: Float
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, this, Resources.getSystem().displayMetrics
    )

/**
 * Int将dp转为px
 */
val Int.dp: Float
    get() = this.toFloat().dp


/**
 * 将byteArray转为hex字符串
 */
fun ByteArray.toHexString(): String =
    joinToString(separator = "") { eachByte -> "%02x".format(eachByte) }


// 在所有实现了LifecycleOwner接口的类中,可以直接使用launch方法
fun LifecycleOwner.launch(
    context : CoroutineContext = EmptyCoroutineContext,
    start : CoroutineStart = CoroutineStart.DEFAULT,
    block : suspend CoroutineScope.() -> Unit
) = lifecycleScope.launch(context,start) { }
